package liuyang.bigeventserver.modules.catetory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import liuyang.bigeventserver.common.Id;
import liuyang.bigeventserver.common.R;
import liuyang.bigeventserver.modules.catetory.entity.Category;
import liuyang.bigeventserver.modules.catetory.mapper.CategoryMapper;
import liuyang.bigeventserver.modules.security.vo.SysUserDetails;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author xconf
 * @since 2024/3/2
 */
@RestController
@RequestMapping("category")
@AllArgsConstructor
@Slf4j
public class CatetoryController {

    private final CategoryMapper categoryMapper;

    /**
     * 新增文章分类
     * https://www.bilibili.com/video/BV14z4y1N7pg/?p=27&vd_source=8bd7b24b38e3e12c558d839b352b32f4
     *
     * 前端只传
     * {
     *     "categoryName": "",
     *     "catetoryAlias": ""
     * }
     * @param category
     * @return
     */
    @PostMapping("add")
    public R add(@RequestBody @Validated(Category.Add.class) Category category) {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final SysUserDetails principal = (SysUserDetails)authentication.getPrincipal();
        //final String username = principal.getUsername();
        final Long userid = principal.getUserid();

        category.setId(Id.nextId());
        category.setCreateUser(userid);// 20240302 因为这里需要userid，所以引入了SysUserDetails extends User（UserDetails），以携带id字段。
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        // 查重
        final LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = Wrappers.<Category>lambdaQuery();
        categoryLambdaQueryWrapper.eq(Category::getCategoryName, category.getCategoryName());
        if (categoryMapper.exists(categoryLambdaQueryWrapper)) {
            return R.error("文章分类已存在");
        }

        // 不重则添加
        categoryMapper.insert(category);
        return R.ok("文章分类添加成功").put("category debug", category);
    }

    /**
     * 查询当前用户创建的文章分类
     * https://www.bilibili.com/video/BV14z4y1N7pg/?p=28&spm_id_from=pageDriver&vd_source=8bd7b24b38e3e12c558d839b352b32f4
     *
     *
     * @return
     */
    @GetMapping("list")
    public R list() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        final Long userid = sysUserDetails.getUserid();

        // 查询
        final LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = Wrappers.<Category>lambdaQuery();
        categoryLambdaQueryWrapper.eq(Category::getCreateUser, userid);
        final List<Category> categories = categoryMapper.selectList(categoryLambdaQueryWrapper);
        return R.ok().put("data", categories);
    }

    /**
     * 获取分类详情
     *
     * @return
     */
    @GetMapping("detail")
    public R detail(Long id) {
        final LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = Wrappers.<Category>lambdaQuery();
        categoryLambdaQueryWrapper.eq(Category::getId, id);
        final Category category = categoryMapper.selectOne(categoryLambdaQueryWrapper);
        return R.ok().put("data", category);
    }

    /**
     * 更新分类详情
     * https://www.bilibili.com/video/BV14z4y1N7pg/?p=30&spm_id_from=pageDriver&vd_source=8bd7b24b38e3e12c558d839b352b32f4
     * https://www.bilibili.com/video/BV14z4y1N7pg/?p=31&vd_source=8bd7b24b38e3e12c558d839b352b32f4
     */
    @PutMapping("update")
    public R update(@RequestBody @Validated(Category.Update.class) Category category) {
        category.setUpdateTime(LocalDateTime.now());

        final LambdaUpdateWrapper<Category> categoryLambdaUpdateWrapper = Wrappers.<Category>lambdaUpdate();
        categoryLambdaUpdateWrapper.eq(Category::getId, category.getId());
        categoryLambdaUpdateWrapper.set(Category::getCategoryName, category.getCategoryName());
        categoryLambdaUpdateWrapper.set(Category::getCategoryAlias, category.getCategoryAlias());
        categoryLambdaUpdateWrapper.set(Category::getUpdateTime, category.getUpdateTime());
        final int updateRow = categoryMapper.update(categoryLambdaUpdateWrapper);
        if (0 == updateRow) {// 实测：就算所有条件都一样，udpateRow也是1不会是0。
            R.error("指定的文章分类不存在");
        }

        return R.ok("文章分类更新成功");
    }

    /**
     * 删除分类
     *
     */
    @GetMapping("delete")
    public R delete(Long id) {// queryString
        log.debug("id = {}" , id);
        final LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = Wrappers.<Category>lambdaQuery();
        categoryLambdaQueryWrapper.eq(Category::getId, id);
        final int deleteRow = categoryMapper.delete(categoryLambdaQueryWrapper);
        if (0 == deleteRow) {
            return R.error("文章分类不存在");
        }
        return R.ok("文章分类删除成功");
    }

}
